<template>
  <li class="comment-item">
    <div class="comment-header">
      <p class="comment-name">{{ comment.name }} {{ new Date(comment.time).toLocaleString() }}</p>
    </div>
    <div class="comment-content">
      <p>{{ comment.text }}</p>
    </div>
    <div class="comment-actions">
      <!--<el-button type="text" icon="el-icon-delete" @click="deleteComment">删除</el-button>-->
      <!--<el-button type="text" icon="el-icon-edit" @click="dialogVisible = true">修改</el-button>-->
    </div>
    <!-- 修改评论的弹窗 -->
    <el-dialog
      title="修改评论"
      :visible.sync="dialogVisible"
      width="30%"
      @close="dialogVisible = false"
    >
      <el-form :model="editForm" ref="editForm">
        <el-form-item label="评论者：" prop="name">
          <el-input v-model="editForm.name" disabled></el-input>
        </el-form-item>
        <el-form-item label="内容：" prop="text">
          <el-input v-model="editForm.text"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitEdit">提交</el-button>
          <el-button @click="dialogVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </li>
</template>

<script>
import axios from "axios";

export default {
  props: {
    comment: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      dialogVisible: false,
      editForm: {
        time: this.comment.time,
        name: this.comment.name,
        text: this.comment.text
      }
    };
  },
  methods: {
    deleteComment() {
      this.editForm.id = this.comment.id;
      this.$emit('delete', this.comment.time);
    },
    submitEdit() {
      this.editForm.id = this.comment.id;
      this.editForm.time = this.comment.time;
      // axios.get('/api/updateComment')
      this.$emit('edit', this.editForm);
      // 隐藏弹窗
      this.dialogVisible = false;
    }
  },
  watch: {
    // 监听 props 中的 comment 变化，以便在评论对象变化时更新 editForm
    comment: {
      handler(newVal) {
        this.editForm = {
          name: newVal.name,
          text: newVal.text
        };
      },
      deep: true // 深度监听对象变化
    }

  }
}
</script>

<style scoped>
.comment-item {
  display: flex;
  flex-direction: column;
  margin-bottom: 20px;
  border: 1px solid #ddd;
  padding: 15px;
  border-radius: 4px;
}

.comment-header {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  margin-bottom: 10px;
}

.comment-name {
  font-weight: bold;
}

.comment-content {
  /* 可以根据需要添加更多样式 */
}

.comment-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
}

/* 你可以使用 Element UI 的 CSS 变量或自定义的 CSS 来进一步定制样式 */
</style>
